<?php

class AccountController extends UController
{
    /**
     * 用户投资列表
     */
    public function actionTranList()
    {
        $page       = $this->_post('page',1);
        $limit      = $this->_post('limit',15);
        $pay_status = $this->_post('pay_status',0);
        $order      = $this->_post('order',1);// 1：按照投资时间排序  0：按照项目到期时间排序
        $data       = User::model()->getTranList($this->userId,$page,$limit,$pay_status,$order);
        $this->setResult($data);
    }

    /**
     * 用户提现金额界面
     */
    public function actionWithDrawShow()
    {
        $this->setResult(User::model()->getWithDraw(
            $this->userId
        ));
    }
    /**
     * 提现申请
     */
    public function actionDoWithDraw()
    {
        $data = array(
            'success'=>0,
            'msg'=>'',
        );
        $params            = array();
        $params['user_id'] = $this->userId;
        $password          = $this->_post('password',null);
        $user              = User::model();
        if(!$user->checkPayPass($this->userId,$password))
            $data['msg'] = '交易密码不正确';
        elseif(!User::model()->checkWithDrawToday($this->userId))
        {
            $data['msg']     = '亲，今天您已经提过一次了';
            $data['success'] = -1;
        }
        else
        {
            $params['card_id']     = $this->_post('card_id');
            $params['amount']      = $this->_post('amount');
            $params['withdraw_no'] ='CG_WITHDRAW_'.time();
            $channel = 'sp';
            $withdrawChannal   = Yii::app()->cache2->get('withdrawChannal');
            if($withdrawChannal)
            {
                $withdrawChannal = json_decode($withdrawChannal);
                if($withdrawChannal->channel == 'll')
                    $channel  = 'll';
            }
            $params['withdraw_type'] = $channel=='sp'?1:2;
            
            $remote                = HttpLib::post($this->javaApi['account_withdraw'],$params);
            $data['msg']           = $remote->errorMsg;
            if($remote!==null && $remote->success)
            {
                Helper::positionRecord('withdraw',$this->userId);
                $data['success'] = 1;
                $data['msg']     = 'ok';
                $info            = $user->findById($this->userId);
                $data['info']  = array(
                    'name'        => $info->name,
                    'amount'      => $params['amount'],
                );
                $cardInfo = $user->getBankCard($this->userId);
                if($cardInfo[0])
                {
                    $data['info']['bankAccount'] = $cardInfo[0]['fullCardNumber'];
                    $data['info']['bankName']    = $cardInfo[0]['bankName'];
                }
            }
        }
        $this->setResult($data);
    }
    /**
     *  提现列表
     */
    public function actionWithdrawList()
    {
        $data = array(
            'success' => 0,
            'msg'     => ' ',
            'list'    => array(),
        );
        $remote = HttpLib::post($this->javaApi['withdraw_list'],array(
            'user_id' => $this->userId,
            'page'    => $this->_post('page',1),
            'limit'   => $this->_post('limit',5),
        ));
        if($remote->success && $remote->result->pageList)
        {
            $data['success'] = 1;
            $data['msg']     = 'ok';
            $data['pageNum'] = $remote->result->pageNum;
            foreach($remote->result->pageList as $v)
            {
                $data['list'][] = array(
                    'id'         => $v->id,
                    'withdrawNo' => $v->number,
                    'amount'     => $v->amount,
                    'bankName'   => $v->bankName,
                    'time'       => $v->gmtCreated,
                    'notice'     => $v->notice?$v->notice:'无',
                    'statusStr'  => $v->statusStr,
                    'status'     => $v->status,
                    'cardLast'   => str_replace(array('*',' '), array('',''), $v->userCardNumber),
                );
            }
        }
        elseif($remote->success)
        {
            $data['success'] = 1;
            $data['msg']     = 'ok';
        }
        elseif($remote->code == 20134)
        {
            $data['success'] = 1;
            $data['msg']     = '暂无提现记录';
        }
        else
            $data['msg'] = $remote->errorMsg;
        $this->setResult($data);
    }
    /**
     * 获取可用的奖励
     */
    public function actionGetReward()
    {
        $this->setResult(User::model()->getUsableRewards($this->userId));
    }
    /**
     * 判断账户余额是否足够支付
     * @return [type] [description]
     */
    public function actionJudgeWaytoPay()
    {
        $data          = array('success'=>0,'msg'=>'');
        $invest_amount = $this->_post('invest_amount');//投资金额
        $pay_needed    = $this->_post('pay_needed');//需要支付的金额
        if(!$invest_amount)
            $data['msg'] = 'invest_amount参数是必传的';
        elseif (!$pay_needed && $pay_needed !=0) {
            $data['msg'] = 'pay_needed参数是必传的';
        }
        else
        {
            $user = User::model();
            $cap = $user->getCapital($this->userId);
            $data['remainMoney'] = $cap['capitalAccountBalance'];
            $accounMoney  = $data['remainMoney'];
            if($accounMoney >= $pay_needed)
                $data['enough']  = 1;
            else
                $data['enough']  = 0;
            $data['success'] = 1;
            $this->setResult($data);
        }
    }

     /**
     * 用户是否可以购买
     */
    public function actionCanBuy()
    {
        $data = array('success'=>0,'msg'=>'');
        $project_id = $this->_post('project_id');
        if(!$project_id)
            $data['msg'] = '参数不合法';
        else
        {
            $data['success'] = 1;
            $model   = Project::model();
            $project = $model->findByPK($project_id);
            $exceptions = array(
                5 => '项目已暂停',
                6 => '销售已结束',
                7 => '项目已提前赎回',
                8 => '已售罄',
                9 => '项目已结束'
            );
            $keys = array_keys($exceptions);
            if(in_array($project->status, $keys))
            {
                $data['msg'] = $exceptions[$project->status];
                $data['ableToBuy'] = -3;
            }
            else
            {
                $user = User::model();
                $projectBalance = $model->getBalance($project_id);//项目可投金额
                if($projectBalance <=0)
                {
                    $data['ableToBuy'] = -2;
                    $data['msg']       = '项目已满额，不能再投资';
                }
                elseif($user->isAbleToBuy($this->userId,$project_id))
                {
                    $data['ableToBuy'] = 1;
                    $data['msg'] = '可以购买';
                }
                else
                {
                    $data['ableToBuy'] = 0;
                    $data['msg']   = '未投资过的用户才可购买新手项目';
                }
            }
        }
        $this->setResult($data);
    }

    public function actionTransferBuy()
    {
        $data = array('success'=>0);
        $project_id = $this->_post('id');
        if(!intval($project_id))
            $data['msg'] = '参数不合法';
        else
        {
            $project = Project::model()->getTransByPK($project_id);
            $exceptions = array(
                6 => '销售结束',
                7 => '提前赎回',
                8 => '已售罄',
                9 => '项目已结束',
            );
            $keys = array_keys($exceptions);
            if(in_array($project->statusCode, $keys))
                $data['msg']     = $exceptions[$project->statusCode];
            elseif($project->userId==$this->userId)
                $data['msg']    = '您不能购买自己转让的项目';
            else
                $data['success'] = 1;
        }
        $this->setResult($data);
    }
    /**
     * 我的资产及我的资产详情
     */
    public function actionIndex()
    {
        $data = array('success' => 1,'msg' => 'ok');
        $user = User::model();
        $cap  = $user->getCapital($this->userId);
        $keys = array('accountTotal','capitalAccountBalance','receivedInterest','withdrawFrozen','receivablePrincipal','receivableInterest','rewardAccountBalance','totalInterest','usedRewardTotal','redeemDemandBalance');
        foreach($keys as $k)
        {
            $data[$k] = $cap[$k];
        }
        $info                      = $user->findById($this->userId);
        $data['name']              = $info->starName;
        $data['realName']          = $info->name;
        $data['mobile']            = $info->mobile;
        $data['identity']          = $info->starIdentity;
        $data['payPassSet']        = $info->resetPayPass;//有没有设置交易密码
        $data['realAuthenticated'] = $info->realAuthenticated;
        $cardinfo                  = $user->getBankCard($this->userId);
        if($cardinfo[0])
        {
            $cinfo                  = $cardinfo[0];
            $data['bankId']         = $cinfo['bankId'];
            $data['bankName']       = $cinfo['bankName'];
            $data['cardNumber']     = $cinfo['cardNumber'];
            $data['pay_limit']      = $cinfo['payLimit']*10000;
            $data['pay_limit_desc'] = '单笔最高额度  '.($cinfo['payLimit']>=1?$cinfo['payLimit']."万元":10000*$cinfo['payLimit'].'元');
        }
        $data['palaceUrl'] = Yii::app()->params['mobile_host'].'/palace';
        $this->setResult($data);
    }

    /**
     * 校验用户密码
     */
    public function actionCheckPass()
    {
        $data = array('success'=>0,'msg'=>'');
        $password = $this->_post('password');
        if(!$password)
        {
            $data['msg'] = '缺少password参数';
        }
        else
        {
            $remote      = HttpLib::post($this->javaApi['user_check_pass'],array('user_id'=>$this->userId,'password'=>$password,'token'=>$this->token));
            $data['msg'] = $remote->errorMsg;
            if($remote->success)
            {
                $data['success'] = 1;
                $data['msg']     = '密码正确';
            }
        }
        $this->setResult($data);
    }
    /**
     * 获取用户实名注册信息和绑定银行卡信息
     */
    public function actionInfo()
    {
        $data                       = array('success'=>0);
        $user                       = User::model();
        $info                       = $user->findById($this->userId);
        $data['isPayPassSet']       = $info->resetPayPass;
        if(!$info->authenticated)//未实名认证  未绑定银行卡
            $data['success']  = -1;
        elseif(!$info->realAuthenticated)//未真正实名认证
        {
            $data['name']         = $info->name;
            $data['starName']     = $info->starName;
            $data['identity']     = $info->identity;
            $data['starIdentity'] = $info->starIdentity;
            $card                 = $user->getBankCard($this->userId);
            $cardinfo             = $card[0];
            if($cardinfo === array())
                $data['success']  = -2;
            elseif(!$cardinfo['supportLL']) //不支持连连
            {
                $data['success']        = -3;
                $data['starCardNumber'] = $cardinfo['starCardNumber'];
                $data['bankName']       = $cardinfo['bankName'];
                $data['msg']            = Yii::app()->params['bankCardNotSupport'];
            }
            else //支持但未绑定连连
            {
                $data['success']        = -6;
                $data['starCardNumber'] = $cardinfo['starCardNumber'];
                $data['bankName']       = $cardinfo['bankName'];
            }
        }
        else //已真正实名认证
        {
            $data['identity']     = $info->identity;
            $data['starIdentity'] = $info->starIdentity;
            $data['name']         = $info->name;
            $data['starName']     = $info->starName;
            $card                 = $user->getBankCard($this->userId);
            $cardinfo             = $card[0];
            if($cardinfo === array())
                $data['success']  = -4;
            elseif(!$cardinfo['supportLL'])
            {
                $data['success']        = -5;
                $data['starCardNumber'] = $cardinfo['starCardNumber'];
                $data['bankName']       = $cardinfo['bankName'];
                $data['msg']            = Yii::app()->params['bankCardNotSupport'];
            }
            elseif($cardinfo['llMark'])//已真正绑卡 不可修改
            {
                $data['success']        = -7;
                $data['starCardNumber'] = $cardinfo['starCardNumber'];
                $data['bankName']       = $cardinfo['bankName'];
            }
            else //支持连连但未绑定连连
            {
                $data['success']        = -8;
                $data['starCardNumber'] = $cardinfo['starCardNumber'];
                $data['bankName']       = $cardinfo['bankName'];
            }
        }
        $this->setResult($data);
    }
    /**
     * 已登陆状态下修改密码
     */
    public function actionResetPassword()
    {
        $data               = array('success'=>0);
        $model              = new ChangePassForm;
        $newpass            = $this->_post('password');
        $oldpass            = $this->_post('old_password');
        $model->password    = $newpass;
        $model->oldPassword = $oldpass;
        if($model->validate())
        {
            $params  = array(
                'user_id'      => $this->userId,
                'old_password' => $oldpass,
                'password'     => $newpass,
            );
            $remote = HttpLib::post($this->javaApi['user_pass_reset'],$params);
            if($remote->success)
            {
                $data['success'] = 1;
                $data['msg']     = '修改密码成功';
            }
            else
                $data['msg'] = $remote->errorMsg;
        }
        else
        {
            foreach($model->getErrors() as $error)
            {
                $data['msg'] = $error[0];
                break;
            }
        }
        $this->setResult($data);
    }

    /**
     * 获取交易信息
     */
    public function actionGetTransactionInfo()
    {
        $data = array('success'=>0,'msg'=>'');
        $transaction_id = intval($this->_post('transaction_id'));
        if(!$transaction_id)
        {
            $data['msg'] = 'transaction_id不能为空';
        }
        else
        {
            $params = array(
                'user_id'        => $this->userId,
                'token'          => $this->token,
                'transaction_id' => $transaction_id,
            );
            $remote      = HttpLib::post($this->javaApi['user_transaction_info'],$params);
            $data['msg'] = $remote->errorMsg;
            if($remote->success)
            {
                $data['success']                      = 1;
                $data['result']                       = array();
                $data['result']['projectName']        = $remote->result->project_name;
                $data['result']['investAmount']       = $remote->result->invest_amount;
                $data['result']['days']               = $remote->result->days;//计息天数
                $data['result']['endTime']            = $remote->result->end_time;
                $data['result']['rate']               = number_format($remote->result->annualized_rate,2,'.','');
                $data['result']['payableInterest']    = number_format($remote->result->payable_interest,2,'.','');
                $data['result']['transactionId']      = $transaction_id;
                $data['result']['totalGains']         = number_format($remote->result->total_gains,2,'.','');//收益 
                $data['result']['totalInterest']      = number_format($remote->result->total_interest,2,'.','');//利息
                $data['result']['rewardAmount']       = $remote->result->reward_amount;//奖励
                $data['result']['startTime']          = $remote->result->start_time;//投资日期
                $data['result']['remainDays']         = $remote->result->remain_days;//剩余天数
                $data['result']['seasonId']           = $remote->result->season_project_id?$remote->result->season_project_id:'';//四季宝id
                $data['result']['minInvestAmount']    = $remote->result->min_invest_amount;//起投金额
                $data['result']['currTransferAmount'] = $remote->result->curr_transfer_amount?$remote->result->curr_transfer_amount:0;//当前转让金额
                $data['result']['transferProjectId']  = $remote->result->transfer_project_id?$remote->result->transfer_project_id:0;//转让项目id
                $data['result']['projectCantTransfer']  = $remote->result->project_cant_transfer?$remote->result->project_cant_transfer:0;//是否提前转让并且是当天
                if($data['result']['endTime']==date('Y-m-d'))
                    $data['result']['projectCantTransfer'] = 1;
                switch ($remote->result->pay_status)
                {
                    case 2:
                        $data['result']['status'] = '提前还本付息';
                        break;
                    case 1:
                        $data['result']['status']     = '已结算';
                        $data['result']['remainDays'] = '已结算';
                        break;
                    case 0:
                        $data['result']['status'] = '投资中';
                        if($remote->result->transfer_code==1)
                            $data['result']['status'] = '转让中';
                        elseif($remote->result->transfer_code==2)
                            $data['result']['status'] = '转让已完成';
                        break;
                    default:
                        $data['result']['status'] = '投资中';
                        break;
                }
                $data['result']['statusCode']      = $remote->result->pay_status;//0:投资中 1：已结算 2：提前还本付息
                $data['result']['transferCode']    = $remote->result->transfer_code===null?0:$remote->result->transfer_code;// 0: 未转让 1:转让中  2: 转让完成 3: 受让
                $data['result']['transferDays']    = 60;
                $data['result']['haveDays']        = (int)$remote->result->have_days;//持有天数
                $data['result']['payedInterest']   = number_format($remote->result->real_pay_interest,2,'.','');
                $data['result']['transferHistory'] = array();
                $data['result']['transferAbleAmount'] = (int)$remote->result->invest_amount;//可转让金额
                $data['judge'] = 1;
                if(strpos(strtolower($remote->result->project_name), 'vip') !== false )
                    $data['judge'] = 0;
                elseif((strtotime($remote->result->end_time)-strtotime($remote->result->start_time))/(24*3600) <=61 )
                    $data['judge'] = 0;
                elseif($remote->result->project_online_time && $remote->result->project_online_time/1000 < strtotime('2015-02-10 00:00:00'))
                    $data['judge'] = 0;
                if($remote->result->transfer_history)
                {
                    foreach($remote->result->transfer_history as $v)
                    {
                        $data['result']['transferHistory'][] = array(
                            'amount' => $v->total_amount,
                            'date'   => date('Y.m.d',strtotime($v->date)),
                        );
                        $data['result']['transferAbleAmount'] -= $v->total_amount;
                    }
                }
            }
        }
        $this->setResult($data);
    }
    /**
     * 付息表
     */
    public function actionInterestList()
    {
        $data           = array('success'=>0);
        $transaction_id = intval($this->_post('transaction_id'));
        if(!$transaction_id)
            $data['msg'] = 'transaction_id不能为空';
        else
        {
            $params = array(
                'user_id'        => $this->userId,
                'transaction_id' => $transaction_id,
            );
            $remote      = HttpLib::post($this->javaApi['transaction_interest'],$params);
            if($remote->success)
            {
                $data['success']     = 1;
                $data['interestList'] = array();
                foreach($remote->result as $interest)
                {
                    $data['interestList'][] = array(
                        'payTime'   => $interest->endTime,
                        'principal' => $interest->payablePrincipal,
                        'days'      => (strtotime($interest->endInterestTime)-strtotime($interest->startTime))/86400+1,
                        'interest'  => number_format($interest->payableInterest,2,'.',''),
                    );
                }
            }
            else
                $data['msg'] = $remote->errorMsg;

        }
        $this->setResult($data);
    }
    /**
     * 分享
     */
    public function actionGetShareTip()
    {
        $data           = array('success' => 1);
        $info           = User::model()->findById($this->userId);
        $shortUrl       = $info->shortUrl;
        $firstLetter    = substr(strtolower($shortUrl), 0,1);
        $data['qrcode'] = 'http://cgtzimage.b0.upaiyun.com/user/sharepics/'.$firstLetter.'/'.$shortUrl.'.jpg';
        switch (SITEMODE) {
            case 'DEVELOP':
                $data['qrcode']  = 'http://cgtzimage.b0.upaiyun.com/user/share/'.$firstLetter.'/'.$shortUrl.'.jpg';
                $data['url']     = 'http://wu.dev.cgtz.com/share/'.$shortUrl.'.html';
                $data['content'] = '我正在用国内最安全的理财APP，快来领取送您的60元礼包！http://wu.dev.cgtz.com/share/'.$shortUrl.'.html【草根投资】';
                break;
            case 'TEST':
                $data['url']     = 'http://115.29.245.28/share/'.$shortUrl.'.html';
                $data['content'] = '我正在用国内最安全的理财APP，快来领取送您的60元礼包！http://115.29.245.28/share/'.$shortUrl.'.html【草根投资】';
                break;
            case 'PRODUCT':
                $data['url']     = 'http://www.cgtz.com/share/'.$shortUrl.'.html';
                $data['content'] = '我正在用国内最安全的理财APP，快来领取送您的60元礼包！http://www.cgtz.com/share/'.$shortUrl.'.html【草根投资】';
                break;
            default:
                # code...
                break;
        }
        $this->setResult($data);
    }
    /**
     * 签到
     */
    public function actionSign()
    {
        $data   = array('success'=>0);
        //今天已经签到
        if(date('Ymd') === Yii::app()->cache2->hget('userSignDate',$this->userId))
        {
            $data['success']    = 2;
            $data['totalScore'] = User::model()->getScore($this->userId);
        }
        else
        {
            $remote = HttpLib::post('score/do/task/sign.json',array('user_id'=>$this->userId),'back_host3');
            if($remote->success)
            {
                $data['success']    = 1;
                $data['score']      = $remote->result;
                $data['totalScore'] = User::model()->getScore($this->userId);
            }
            elseif($remote->code==21009)
            {
                $data['success']    = 2;
                $data['totalScore'] = User::model()->getScore($this->userId);
            }
            else
                $data['msg']  = $remote->errorMsg;
        }
        $this->setResult($data);
    }
    /**
     * 用户推荐列表
     */
    public function actionGetRecommendList()
    {
        $data  = array('success'=>0);
        $page  = $this->_post('page',1);
        $limit = $this->_post('limit',10);
        $cache = Yii::app()->cache_new;
        if(!$cache->hget('userRecommendListTag',$this->userId))
        {
            $remote = HttpLib::get('account/init/recommend/list.json',array(
                'user_id' => $this->userId,
            ));
            if(!$remote->success)
            {
                $data['msg'] = $remote->errorMsg;
                $this->setResult($data);
            }
        }
        $k     = 'userRecommendList.'.$this->userId;
        $count = $cache->llen($k);
        $list  = $cache->lrange($k,($page-1)*$limit,$page*$limit-1);
        $recommandlist = array();
        $data['totalCount'] = $count;
        $data['pageNum']    = (int)(($count+$limit-1)/$limit);
        if($list)
        {
            $user = new User;
            foreach($list as $v)
            {
                $info = $user->getUserInfo($v);
                if($info)
                {
                    $recommandlist[] = array(
                        'mobile'   => $info->mobileStr,
                        'invest'   => $info->invest?1:0,
                    );
                }
            }
            $data['list'] = $recommandlist;
        }
        $data['success'] = 1;
        $this->setResult($data);
    }

}
